package com.cgs.query.server.controller

import com.cgs.query.connection.ConnectionFactory
import com.cgs.query.domain.QuerySource
import com.cgs.query.exception.QueryException
import com.cgs.query.service.IQuerySourceService
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiParam
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import java.sql.Connection

@RestController
@RequestMapping("/source")
@Api(description = "源管理模块")
class QuerySourceController {

    @Autowired
    private lateinit var querySourceService: IQuerySourceService
    @Autowired
    private lateinit var connectionFactory: ConnectionFactory

    @GetMapping("/{id}")
    @ApiOperation(value = "通过源id查询")
    fun findOne(@ApiParam(value = "编号", required = true) @PathVariable id: String) = querySourceService.findById(id)

    @PostMapping("/")
    @ApiOperation(value = "修改源")
    fun save(@ApiParam(value = "源定义", required = true) @RequestBody source: QuerySource) = querySourceService.save(source)

    @DeleteMapping("/{id}")
    @ApiOperation(value = "通过源id删除")
    fun delete(@ApiParam(value = "编号", required = true) @PathVariable id: String) = querySourceService.delete(id)

    @GetMapping("/list")
    @ApiOperation(value = "展示源列表")
    fun findAll(@ApiParam(value = "当前页数") @RequestParam(required = false, defaultValue = "0") pn: Int,
                @ApiParam(value = "每页大小") @RequestParam(required = false, defaultValue = "5") ps: Int) = querySourceService.findAll(pn, ps)

    @GetMapping("/list/unLock")
    @ApiOperation(value = "获取没有锁定的列表")
    fun findByUnLock(@ApiParam(value = "项目名称") @RequestParam(required = false, defaultValue = "5") projectName: String) = querySourceService.findByUnLock(projectName)

    @PostMapping("/test")
    @ApiOperation(value = "测试")
    fun delete(@ApiParam(value = "源定义", required = true) @RequestBody source: QuerySource) {
        var connection: Connection? = null
        try {
            connection = connectionFactory.getConnection(source)
        } catch (e: Exception) {
            throw QueryException("连接失败！")
        } finally {
            connection?.close()
        }
    }
}